<?php
/**
 * Description of Yxb 小程序测试接口
 * @author rhett_ni<415080528@qq.com>
 */
namespace Home\Controller;
use Common\Extend\Xiaochengxu\WXLoginHelper;
use Think\Controller;

class YxbController extends Controller {

    private $app_api_url;
    private $api_url;
    private $image_url;
    private $brm_id;

    public function __construct()
    {
        $this->api_url = 'http://api.yy.258.com'; //运营系统正式接口
        $this->app_api_url = 'https://appservice.258.com'; //用户系统正式接口
        $this->image_url = 'http://yy.258.com'; //图片正式地址
        $debug = 1;
        if($debug){
            $this->api_url = 'http://api.yxbyy.beta.258.com'; //运营系统测试接口
            $this->app_api_url = 'http://app.beta.258.com'; //用户系统测试接口
            $this->image_url = 'http://yxbyy.beta.258.com'; //图片测试地址
        }
        $this->brm_id = I('brm_id');
    }

    /**
     * 意向案源确认函
     */
    public function letter(){
//        $created_at = '20171208 20:49:10';
//        $is_expire = checkIsExpireDay($created_at,5);
//        _debug($is_expire);
        $url = '/YxbApplet/getConfirmLetterList';
        $p=I('p',1);
        $limit=I('limit',20);
        $brm_id = $this->brm_id;
        $status = I('status', 2);
        $data = array(
            'brm_id' => $brm_id,
            'status' => $status,
            'p' => $p,
            'limit' => $limit,
        );
        $res = $this->app_api($url, $data);

        if ($res['result_code'] == 'app_success') {
            if($res['result_data']['list']) {
                foreach ($res['result_data']['list'] as &$v) {
                    $v['content'] = json_decode($v['content'], true);
                    $v['content']['call_record'] = $v['content']['call_record'] ? json_decode(htmlspecialchars_decode($v['content']['call_record'])) : '';
                    //$v['yxcustomer'] = $this->getYxcustomerInfo($v['content']['brm_id'],$v['content']['mate_id']);
                    unset($v);
                }
                //_debug($res);
                _output($res['result_data']);
            }else{
                _output(['total'=>0,'list'=>[]]);
            }
        } else {
            _output($res, 201, $res['result_info']);
        }

    }

    /**
     * 意向客户详情
     */
    public function yxcustomerinfo(){
        $brm_id = $this->brm_id;
        $mate_id=I('mate_id');
        $result = $this->getYxcustomerInfo($brm_id, $mate_id);
        // dump($result['mate_info']['approach_reply']);
        foreach ($result['mate_info']['approach_reply'] as $key => $value) {
            $file_list = json_decode($value['fileinfo'],true);
            foreach ($file_list as $k => $v) {
                $src = str_replace("http://", "https://", $v['src']);
                $file_list[$k]['src'] = $src;
            }
            $result['mate_info']['approach_reply'][$key]['fileinfo'] = $file_list;
        }
        _output($result);
    }

    /**
     * 获取意向客户详情
     * @param $brm_id
     * @param $mate_id
     */
    function getYxcustomerInfo($brm_id, $mate_id){
        $url = '/customer/getCustomerInfo';
        $data = array(
            'brm_id'=>$brm_id,
            'mate_id'=>$mate_id,
        );
        $res_data = $this->get_api($url, $data);
        // dump($res_data);
        // $holidays = getHoliday();
        foreach ($res_data['r']['contacts'] as &$item) {
            $item['linkman_role_name'] = linkman_role($item['linkman_role_id']);
            unset($item);
        }

        $res_data['r']['follows'][0]['follow_prop'] = $res_data['r']['follows'][0]['follow_prop'] ? json_decode($res_data['r']['follows'][0]['follow_prop'],true) : '';
        $res_data['r']['mate_info']['customer_mate_follow_one']['follow_prop'] = $res_data['r']['mate_info']['customer_mate_follow_one']['follow_prop'] ? json_decode($res_data['r']['mate_info']['customer_mate_follow_one']['follow_prop'],true) : '';
        $res_data['r']['mate_info']['customer_mate_follow_one']['next_approached_at'] = $res_data['r']['mate_info']['customer_mate_follow_one']['next_approached_at'] ?  $res_data['r']['mate_info']['customer_mate_follow_one']['next_approached_at'] : $res_data['r']['mate_info']['customer_mate_follow_one']['next_approached_next'];

        $category = [];
        if($res_data['r']['info']['category_name1']) {
            $category[] = $res_data['r']['info']['category_name1'];
        }
        if($res_data['r']['info']['category_name2']) {
            $category[] = $res_data['r']['info']['category_name2'];
        }
        $category = implode('、',$category);

        $examine_status = [
            '已跟进',
            '同意退回',
            '拒绝退回'
        ];

        if($res_data['r']['mate_return']['return_explain']) {
            $res_data['r']['mate_return']['return_explain'] = json_decode(htmlspecialchars_decode($res_data['r']['mate_return']['return_explain']), true);
            $res_data['r']['mate_return']['return_explain']['reason'] = $res_data['r']['mate_return']['return_explain']['reason'] ? explode(',', $res_data['r']['mate_return']['return_explain']['reason']) : [];
            $res_data['r']['mate_return']['examine_status_name'] = $examine_status[$res_data['r']['mate_return']['examine_status']];
            $res_data['r']['mate_return']['created_at']['date'] = date('Y.m.d H:i', strtotime($res_data['r']['mate_return']['created_at']['date']));
        }

        //是否超过三个工作日
        // $created_at = date('Ymd H:i:s', strtotime($res_data['r']['mate_info']['examine_at']));
        //_debug($created_at);
        //$created_at = '20171231 16:37:43';
        // $expire_days = newCheckIsExpire($created_at,$holidays);
        $created_at = date('Ymd H:i:s', strtotime($res_data['r']['mate_info']['examine_at']));
        // dump($item['examine_at']);
        $now_date = date('Ymd H:i:s');
        $expire_days = diffBetweenTwoDays($created_at,$now_date);
        $is_expire = 1;
        $is_expire_apply_new = 2;//用来判断时间
        // dump($expire_days);
        $is_expire_apply = 2;
        // dump($expire_days);
        if($expire_days < 3){
            $is_expire = 0;
            $expire_date = strtotime($res_data['r']['mate_info']['examine_at'])+3*86400;
        }
        // dump($res_data['r']['mate_info']['examine_at']);
        // dump($expire_date);
        if($is_expire){
            if(3 < $expire_days&&$expire_days < 5){
                $is_expire_apply_new = $is_expire_apply = 0;
                $expire_date = strtotime($res_data['r']['mate_info']['examine_at'])+5*86400;    
            }else{
                $is_expire_apply_new = $is_expire_apply = 1;
            }
            //1是,0否超过申诉期（第4、5天为申诉期）
        }else{
            $is_expire_apply_new = $is_expire_apply = 2;//2撮合期（3天内）
        }
        // dump($is_expire_apply);exit;
        //已申诉过
        if($res_data['r']['mate_return']['return_explain']['reason']){
            $is_expire_apply = 3;
        }

        //拓客系统可以进行接洽的回复，回复后，会员中心可以再次进行接洽
        $reply = $res_data['r']['mate_info']['approach_reply'];
        $need_approach = 1;
        if(count($reply)) {
            if ($reply[count($reply) - 1]['reply'] == '') {
                $need_approach = 0;
            }
        }

        //测试
        //$is_expire_apply = 0;

        $result = [
            'expire_date' => $expire_date,
            'company_name' => $res_data['r']['info']['company_name'],
            'category' => $category,
            'product' => $res_data['r']['info']['major_product'],
            'business_range' => $res_data['r']['info']['business_range'],
            'city' => $res_data['r']['info']['province_name'].$res_data['r']['info']['city_name'],
            'address' => $res_data['r']['info']['address'],
            'business_model' => $res_data['r']['info']['business_model'],
            'company_build' => $res_data['r']['info']['company_build_at'],
            'contacts'=>$res_data['r']['contacts'],
            'contacts_num'=>count($res_data['r']['contacts']),
            'contact_name'=>$res_data['r']['contacts'][0]['name'],
            'contact_mobile'=>$res_data['r']['contacts'][0]['mobile']?$res_data['r']['contacts'][0]['mobile']:$res_data['r']['contacts'][0]['telephone'],
            //'sale_user_name'=>$res_data['r']['follows'][0]['user_one']['name']?$res_data['r']['follows'][0]['user_one']['name']:'',
            'sale_user_name'=>$res_data['r']['info']['sale_user_name']?$res_data['r']['info']['sale_user_name']:'',
            'follows'=>$res_data['r']['follows'],
            'follow_id'=>$res_data['r']['follows'][0]['customer_mate_follow_id'],
            'approached_advise'=>$res_data['r']['follows'][0]['approached_advise'],//接洽建议
            'next_approached_at'=>$res_data['r']['follows'][0]['next_approached_at']?$res_data['r']['follows'][0]['next_approached_at']:$res_data['r']['follows'][0]['next_approached_text'],//建议接洽时间
            'approached'=>$res_data['r']['follows'][0]['approached'], //接洽情况
            'approached_at'=>$res_data['r']['follows'][0]['approached_at'], //接洽时间
            'fileinfo'=>$res_data['r']['follows'][0]['fileinfo'], //附件内容json格式
            'avatar_url'=>$res_data['r']['follows'][0]['user_one']['avatar_url']?$this->image_url.$res_data['r']['follows'][0]['user_one']['avatar_url']:'',
            'mate_return'=>$res_data['r']['mate_return'],
            'mate_info'=>$res_data['r']['mate_info'],
            'follow_prop'=>$res_data['r']['mate_info']['customer_mate_follow_one']['follow_prop'],
            'customer_mate_follow_one'=>$res_data['r']['mate_info']['customer_mate_follow_one'],
            'is_expire'=>$is_expire ? 1 : 0,
            'is_expire_apply'=>$is_expire_apply ? $is_expire_apply : 0,
            'need_approach'=>$need_approach,
            'is_expire_apply_new' =>$is_expire_apply_new?$is_expire_apply_new:0
        ];
        return $result;
    }
    
    public function test(){
        // echo(11);return;
        echo newCheckIsExpire('20180131');
    }
    /**
     * 意向案源确认函详情
     */
    public function letterInfo(){
        $url = '/YxbApplet/getConfirmLetterDetail';
        $id = I('id');
        $brm_id = $this->brm_id;
        $data = array(
            'brm_id' => $brm_id,
            'id' => $id
        );
        $res = $this->app_api($url, $data);
        if ($res['result_code'] == 'app_success') {
            $res['result_data']['content'] = json_decode($res['result_data']['content'],true);
            $res['result_data']['content']['next_content'] = is_null($res['result_data']['content']['next_content']) ? '' : $res['result_data']['content']['next_content'];
            $res['result_data']['content']['call_record'] = $res['result_data']['content']['call_record'] ? json_decode(htmlspecialchars_decode($res['result_data']['content']['call_record'])) : '';
            $res['result_data']['content']['next_approached_at'] = $res['result_data']['content']['next_approached_at']?$res['result_data']['content']['next_approached_at']:$res['result_data']['content']['next_approached_text'];
            $res['result_data']['yxcustomer'] = $this->getYxcustomerInfo($res['result_data']['content']['brm_id'],$res['result_data']['content']['mate_id']);
            //确认意向函确认
            $this->confirmCusotmer($brm_id, $res['result_data']['content']['mate_id'], $res['result_data']['id']);
            _output($res['result_data']);
        } else {
            _output($res, 201, $res['result_info']);
        }
    }

    function confirmCusotmer($brm_id, $mate_id, $id){
        $url = '/customer/confirmCusotmer';

        $data = array(
            'brm_id' => $brm_id,
            'mate_id' => $mate_id
        );
        $res_data = $this->get_api($url, $data);
        if($res_data['s']){
            $url = '/YxbApplet/getConfirmLetterDetail';
            $data = array(
                'brm_id' => $brm_id,
                'id' => $id
            );
            $res = $this->app_api($url, $data);
            if ($res['result_code'] == 'app_success') {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
    /**
     * 确认函确认
     */
    public function subLetter(){
        $url = '/customer/confirmCusotmer';

        $brm_id = $this->brm_id;
        $mate_id = I('mate_id');
        $id = I('id');
        $data = array(
            'brm_id' => $brm_id,
            'mate_id' => $mate_id
        );
        $res_data = $this->get_api($url, $data);
        if($res_data['s']){
            $url = '/YxbApplet/getConfirmLetterDetail';
            $data = array(
                'brm_id' => $brm_id,
                'id' => $id
            );
            $res = $this->app_api($url, $data);
            if ($res['result_code'] == 'app_success') {
                _output();
            } else {
                _output([],201);
            }
        }
        _output([],201);
    }

    /**
     * 退回意向案源确认函列表
     */
    public function backYx(){
        $data = I();
        $brm_id = $this->brm_id;//2013660
        $limit  = empty($data['limit'])  ? 20 :$data['limit'];
        $page   = empty($data['page'])   ? 1  :$data['page'];
        $type   = I('type', 1); //0  待审  1  成功  2 拒绝
        $mate_company_name = empty($data['mate_company_name'])     ? '' :$data['mate_company_name'];

        $url = '/customer/returnCustomerList';

        $post_data = array(
            'brm_id' => $brm_id,
            'limit' => $limit,
            'page' => $page,
            'type' => $type,
            'mate_company_name' => $mate_company_name,
        );
        $res_data = $this->get_api($url, $post_data);
        $examine_status = [
            '申诉中',
            '同意退回',
            '拒绝退回'
        ];
        //_debug($res_data);
        if($res_data['s']){
            //_debug($res_data['r']);
            foreach ($res_data['r']['data'] as &$v) {
                $v['mate_customer_one']['created_at'] = date('m.d H:i', strtotime($v['mate_customer_one']['created_at']));
                //$v['yxcustomer'] = $this->getYxcustomerInfo($v['mate_customer_one']['brm_id'],$v['customer_mate_id']);
                $v['return_one']['return_explain'] = json_decode(htmlspecialchars_decode($v['return_one']['return_explain']), true);
                $v['return_one']['return_explain']['reason'] = $v['return_one']['return_explain']['reason'] ? explode(',', $v['return_one']['return_explain']['reason']) : [];
                $v['return_one']['return_explain']['count'] = count($v['return_one']['return_explain']['reason']);
                $v['return_one']['examine_status_name'] = $examine_status[$v['return_one']['examine_status']];
                $v['mobile_status_name'] = mobile_status($v['customer_mate_follow_one']['mobile_status']);
                unset($v);
            }
            //_debug($res_data);
            _output($res_data['r']);
        }
        _output([],201);
    }

    /**
     * 微信授权绑定
     * @author rhett_ni<415080528@qq.com>
     */
    public function wxBind(){
        $data = I('post.');
        if(!$data['openId']||!$data['unionId']||!$data['uid']){
            _output([],201,'参数缺失');
        }
        $url = '/YxbApplet/bindWeChat';
        $res = $this->app_api($url,$data);
        _log($res,'wx');
        if($res['result_code']=='app_success'){
            _output($res);
        }else{
            _output($res,201,$res['result_info']);
        }
    }

    /**
     * 退出登录
     * @author rhett_ni<415080528@qq.com>
     */
    function logout(){
        $post_data = I('post.');
        $data = array (
            'openId' => $post_data['openId'],
            'uid' => $post_data['uid'],
        );
        if(!$data['uid']){
            _output([],201,'参数缺失');
        }
        if($data['openId']) {
            $url = '/YxbApplet/unbindWeChat';
            $res = $this->app_api($url, $data);
            if ($res['result_code'] == 'app_success') {
                _output($res);
            } else {
                _output($res, 201, $res['result_info']);
            }
        }else{
            _output();
        }
    }

    /**
     * 运营系统接口请求
     * @param $url
     * @param $data
     * @return mixed|\type
     */
    function get_api($url,$data){
        $url = $this->api_url.$url;
        $brm_id = $this->brm_id;
        $token = md5($brm_id . '_' . md5(substr(time(), 0, 4)) . '_PlIM-lJ54-940R-J2K8-JudM');
        $data['token'] = $token;
        $res = post($url, $data);
        // dump($res);
        $res_data = json_decode($res, true);
        return $res_data;
    }

    /**
     * 用户系统接口请求
     * @param $url
     * @param $data
     * @return mixed|\type
     */
    function app_api($url,$data){
        $temp = $url;
        $url = $this->app_api_url.$url;
        $ret_data = json_encode($data);
        $time = time();
        $platform = 'yxbApplet';
        $version = 1;
        $token = APP_TENKEN_KEY.$time.$platform.$version.$ret_data;
        $post_data = [
            'token' => md5(md5($token)),
            'time' => $time,
            'platform' => $platform,
            'version' => $version,
            'data' => $ret_data,
            'server_version' => 1,
        ];
        $res = getRemoteData($url,$post_data);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 微信授权自动登录
     * @author rhett_ni<415080528@qq.com>
     */
    public function wxlogin(){
        $code = I("code", '', 'htmlspecialchars_decode');
        $rawData = I("rawData", '', 'htmlspecialchars_decode');
        $signature = I("signature", '', 'htmlspecialchars_decode');
        $encryptedData = I("encryptedData", '', 'htmlspecialchars_decode');
        $iv = I("iv", '', 'htmlspecialchars_decode');

        //获取openId和unionId
        $wxHelper = new WXLoginHelper();
        $data = $wxHelper->checkLogin($code, $rawData, $signature, $encryptedData, $iv);
        _log($data,'wx');

        if(!$data['openId']){
            _output([],201,'授权失败');
        }
        unset($data['watermark']);
        unset($data['session3rd']);

        $url = '/YxbApplet/wechatLogin';
        $res = $this->app_api($url,['openId'=>$data['openId']]);

        if($res['result_code']=='app_success'){
            $res['result_data']['uid'] = $res['result_data']['uid'] ? $res['result_data']['uid'] : 0;
            $res['result_data']['brm_id'] = $res['result_data']['brm_id'] ? $res['result_data']['brm_id'] : 0;
            _output(array_merge($data,$res['result_data']));
        }else{
            $uid = I('uid');
            if($uid){
                $url = '/YxbApplet/bindWeChat';
                $data['uid'] = $uid;
                $res = $this->app_api($url,$data);
                _log($res,'wx');
                if($res['result_code']=='app_success'){
                    _output(array_merge($data,$res['result_data']));
                }else{
                    _output($data,202,$res['result_info']);
                }
            }
            _output($data,203,$res['result_info']);
        }
    }

    /**
     * 发送验证码
     * @author rhett_ni<415080528@qq.com>
     */
    public function sendcode(){
        $mobile = I('mobile');
        $url = '/YxbApplet/sendMobileCode';
        $data = [
            'mobile' => $mobile,
            'type' => 11,
        ];
        $res = $this->app_api($url,$data);

        if($res['result_code']=='app_success'){
            _output($res);
        }else{
            _output($res,201,$res['result_info']);
        }
    }

    /**
     * 手机验证码／账号密码登陆
     * @author rhett_ni<415080528@qq.com>
     */
    public function login(){
        $code = I('code');
        $mobile = I('mobile');
        $password = I('password');
        $url = '/YxbApplet/lgoinRegister';
        $data = [
            'mobile' => $mobile,
            'code' => $code,
            'password' => md5($password)
        ];
        if(!$password){
            unset($data['password']);
        }
        $res = $this->app_api($url,$data);
        if($res['result_code']=='app_success'){
            _output($res['result_data']);
        }else{
            $msg = $res['result_info'];
            if($password){
                $msg = "会员名或密码错误";
            }
            _output([],201,$msg);
        }
    }

    /**
     * 营销宝首页数据
     */
    public function yx(){
        //综合统计
        $url = '/customer/getMateCountForType';

        $brm_id = $this->brm_id;
        $data = array(
            'brm_id' => $brm_id
        );
        $res_data = $this->get_api($url, $data);

        $res_data['r'][2] = jztotal($res_data['r'][2]);

        //客户统计
        $url = '/YxbApplet/CoustomerCount';
        $app_data = [
            'brm_id' => $brm_id,
        ];

        $app_api_res = $this->app_api($url, $app_data);
        if ($app_api_res['result_code'] == 'app_success') {
            $app_data = $app_api_res['result_data'];
        }

        //待评论数
        $url = '/yxbApplet/allMateFollowList';
        $p = I('p',1);
        $limit = I('limit',100);
        $data = [
            'brm_id' => $brm_id,
            'p' => $p,
            'limit' => $limit
        ];

        $record_data = $this->get_api($url, $data);
        $result['head'] = [
            'total' => $res_data['r'][4] ? $res_data['r'][4] : 0,
            'djq' => $res_data['r']['matchTotal'] ? $res_data['r']['matchTotal'] : 0,
            'dpj' => $res_data['r']['commentTotal'] ? $res_data['r']['commentTotal'] : 0,
            'dgj' => $record_data['r']['notReplyTotal'] ? $record_data['r']['notReplyTotal'] : ''
        ];
        $result['zhonghe'] = [
            [
                'id' => '1',
                'num' => $res_data['r'][3]+$res_data['r'][4] ? $res_data['r'][3]+$res_data['r'][4] : 0,
                //'message' => '人工筛选客户数',
            ],
            [
                'id' => '2',
                'num' => $res_data['r'][2]?$res_data['r'][2]:0,
                //'message' => '精准匹配客户数'
            ],
            [
                'id' => '3',
                'num' => $res_data['r'][1]?$res_data['r'][1]:0,
                //'message' => '行业大数据'
            ],[
                'id' => '4',
                'num' => $app_data['pczsl_sum'] ? $app_data['pczsl_sum'] : 0,
                //'message' => '搜索引擎收录量',
            ],
            [
                'id' => '5',
                'num' => $app_data['pcsxs_sum'] ? $app_data['pcsxs_sum'] : 0,
                //'message' => 'PC端上线词'
            ],
            [
                'id' => '6',
                'num' => $app_data['mobsxs_sum'] ? $app_data['mobsxs_sum'] : 0,
                //'message' => '移动端上线词'
            ],
            [
                'id' => '7',
                'num' => $app_data['reg_count'] ? $app_data['reg_count'] : 0,
                //'message' => '成功注册网站数',
            ],
            [
                'id' => '8',
                'num' => $app_data['generation_count'] ? $app_data['generation_count'] : 0,
                //'message' => '代编商情数'
            ],
            [
                'id'=> '9',
                'num'=> $app_data['extensionWord_count'] ? $app_data['extensionWord_count'] : 0,
                //'message'=> '站内推广词'
            ]
        ];
        _output($result);
    }

    /**
     * 营销宝首页数据
     */
    public function my(){
        $url=$this->api_url.'/customer/getMateCountForType';
        $brm_id = $this->brm_id;//2013693  2013392

        $key = md5('my_'.http_build_query(I('post.')).$url);
        $token = md5($brm_id . '_' . md5(substr(time(), 0, 4)) . '_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token' => $token,
            'brm_id' => $brm_id,
        );
        $res = post($url, $data);
        $res_data = json_decode($res, true);

        //_debug($res_data);
        $res_data['r'][2] = jztotal($res_data['r'][2]);

        $mateCountData = [
            'djq' => $res_data['r']['matchTotal']?$res_data['r']['matchTotal'].'接洽反馈期':'',
            'dpj' => $res_data['r']['commentTotal']?$res_data['r']['commentTotal'].'意向确认期':'',
            'dgj' => $res_data['r']['notReplyTotal']?$res_data['r']['notReplyTotal']:''
        ];

        if($mateCountData['djq']&&$mateCountData['dpj']){
            $mateMsg = $mateCountData['djq'].'，'.$mateCountData['dpj'];
        }else if($mateCountData['djq']){
            $mateMsg = $mateCountData['djq'];
        }else{
            $mateMsg = $mateCountData['dpj'];
        }

        $url = '/YxbApplet/yxbInfo';
        $post_app_data = [
            'brm_id' => $brm_id,
        ];
        $key = md5('my2_'.http_build_query(I('post.')).$url);
        $app_api_res = $this->app_api($url, $post_app_data);
        if ($app_api_res['result_code'] == 'app_success') {
            $app_data = $app_api_res['result_data'];
        }

        $result['head']['headBag'] = '/dist/images/headPic.jpg';
        $result['head']['company_name'] = $app_data['company_name'];
        if($app_data['is_yxb']) {
            if($app_data['year']==0){
                $app_data['year'] = 1;
            }
            $result['head']['year'] = $app_data['is_yxb'] ? '营销宝会员第' . $app_data['year'] . '年':'';
            $result['head']['expire'] = $app_data['is_yxb'] ? date('Y年m月d日', $app_data['end_time']) . '到期' : '';
        }

        $url=$this->api_url.'/yxbApplet/allMateFollowList';
        $p=I('p',1);
        $limit=I('limit',500);

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'p'=>$p,
            'limit'=>$limit
        );
        $res = post($url,$data);
        $record_data=json_decode($res,true);

        //确认函总数
        $url = '/YxbApplet/getConfirmLetterList';
        $p=I('p',1);
        $limit=I('limit',2);
        $brm_id = $this->brm_id;
        $data = array(
            'brm_id' => $brm_id,
            'status' => 1,
            'p' => $p,
            'limit' => $limit,
        );
        $letter_res = $this->app_api($url, $data);
        $letter_num = $letter_res['result_data']['total'];

        //退回意向申诉数
        $url = '/customer/returnCustomerList';
        $post_data = array(
            'brm_id' => $brm_id,
            'limit' => 20,
            'page' => 1,
            'type' => 0,
        );
        $return_customer_data = $this->get_api($url, $post_data);
        $return_num = $return_customer_data['r']['total'];
        $result['zhonghe'] = [
            [
                'url'=> '../my/intention/intention?type=4',
                'num'=> $res_data['r'][4]?$res_data['r'][4]:0,
                'name'=> '潜在买家库',
                'msg'=> $mateMsg,
                'icon'=>'icon-kehu1'
            ],
            [
                'url'=> '../my/record/record',
                'num'=> $record_data['r']['count']?$record_data['r']['count']:0,
                'name'=> '开发记录查看',
                'msg'=> $record_data['r']['notReplyTotal'] ? $record_data['r']['notReplyTotal'].'待评论':'',
                'icon'=>'icon-jilu'
            ],
            [
                'url'=> '../my/record/record',
                'num'=> $res_data['r']['completeEvaluateTotal']?$res_data['r']['completeEvaluateTotal']:0,
                'name'=> '服务评价查询',
                'msg'=>'',
                'icon'=>'icon-jilu'
            ],
            [
                'url'=> '../my/intention/intention?type=3',
                'num'=> $res_data['r'][3]+$res_data['r'][4] ? $res_data['r'][3]+$res_data['r'][4] : 0,
                'name'=> '人工筛选客户',
                'msg'=>'',
                'icon'=>'icon-luzhi'
            ],
            [
                'url'=> '../my/intention/intention?type=2',
                'num'=> $res_data['r'][2]?$res_data['r'][2]:0,
                'name'=> '精准匹配客户',
                'msg'=>'',
                'icon'=>'icon-jingzhunpipeicopy'
            ],
            [
                'url'=> '../my/intention/intention?type=1',
                'num'=> $res_data['r'][1]?$res_data['r'][1]:0,
                'name'=> '行业大数据',
                'msg'=>'',
                'icon'=>'icon-xiaoshou'
            ],
            [
                'url'=> '../my/letter/letter',
                'num'=> $letter_num,
                'name'=> '意向案源确认函',
                'msg'=> $letter_num ? '已接收'.$letter_num.'家' : '',
                'icon'=>'icon-xiaoshou'
            ],
            [
                'url'=> '../my/backyx/backyx',
                'num'=> $return_num?$return_num:0,
                'name'=> '退回意向案源',
                'msg'=>'',
            ]
        ];
        _output($result);
    }

    /**
     * 意向客户列表
     */
    public function yxcustomer(){
        $type = I('type',4);
        $brm_id = $this->brm_id;
        $page = I('page',1);
        $limit = I('limit',50);
        header("Content-type: text/html; charset=utf-8");
        $url=$this->api_url.'/customer/getMatelist';
        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $dispose_status=I('status',3);
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'page'=>$page,
            'type'=>$type, //1行业大数据 2精准 3人工筛选 4意向
            'limit'=>$limit,
            'dispose_status'=>$dispose_status, //0全部 1成交期 2评论期 3未接洽 (旧版1已处理 2未处理  0或空为全部)
        );
        //针对501186521做电话联系人显示
        if($brm_id!='501186521'){
            $data['is_hide_tel'] = 1; 
            $data['is_hide_name'] = 1; 
        }

        $res = post($url,$data);
        $res_data=json_decode($res,true);
        if($type==2) {
            $res_data['r']['total'] = jztotal($res_data['r']['total']);
        }

        $datas = [
            'total'=>$res_data['r']['total'],
            'pend'=>[],
            'deal'=>[],
        ];
        //_debug($res_data['r']['data']);
        // $holidays = getHoliday();
        foreach ($res_data['r']['data'] as $key=>&$item) {
            //是否超过三个工作日
            $created_at = date('Ymd H:i:s', strtotime($item['examine_at']));
            $now_date = date('Ymd H:i:s');
            // $is_expire = 1;
            // $expire_days = newCheckIsExpire($created_at,$holidays);
            $expire_days = diffBetweenTwoDays($created_at,$now_date);
            // dump( $expire_days );
            $is_expire = 1;
            $is_expire_apply = 2;
            if($expire_days < 3){
                $is_expire = 0;
            }
            
            if($is_expire){
                if(3 < $expire_days&&$expire_days < 5){
                    $is_expire_apply = 0;    
                }else{
                    $is_expire_apply = 1;
                }
                //1是,0否超过申诉期（第4、5天为申诉期）
            }else{
                $is_expire_apply = 2;//2撮合期（3天内）
            }

            //已申诉过
            if($res_data['r']['mate_return']['return_explain']['reason']){
                $is_expire_apply = 3;
            }

            if($type==1||$type==2) {
                $datas['pend'][] = [
                    'company_name' => $item['company_name'],
                    'mate_id' => $item['customer_id'],
                    'brm_id'=> $item['brm_id'],
                    'address' => $item['address'],
                    'evaluate_level' => '',
                    'u_name' => $item['contact_one']['name'],
                    'mobile' => $item['contact_one']['mobile'],
                    't_name' => '',
                    'real_mobile'=>$item['contact_one']['mobile']?1:0
                ];

            }elseif($type==4) {
                if (($item['approached_at'] == '' || $item['approached_at'] == 'NULL') && $item['evaluate_level'] == 0) {
                    $status_name = '接洽反馈期';
                    $status = 1;  //新
                    $list_type = "pend";
                } elseif ($item['evaluate_level'] == 0) {
                    $status_name = '意向确认期';
                    $status = 2;
                    $list_type = "pend";
                } else {
                    $status_name = '';
                    $status = 3;
                    $list_type = "deal";
                }
                if($dispose_status==1) {
                    $status_name = '评价期';
                    $status = 3;
                    $list_type = "deal";
                }else if($dispose_status==2){
                    $list_type = "pend";
                    $status_name = '意向确认期';
                    $status = 2;
                }else if($dispose_status==3){
                    $list_type = "pend";
                    $status_name = '接洽反馈期';
                    $status = 1;
                }

                //拓客系统可以进行接洽的回复，回复后，会员中心可以再次进行接洽
                if(!$is_expire){
                    $list_type = "pend";
                    $status_name = '接洽反馈期';
                    $status = 1;
                }
                // dump($is_expire);
                $status_name = $is_expire==1 ? '意向确认期' : $status_name;
                $status_name = $is_expire_apply== 1 || $item['evaluate_level']>0? '评价期' : $status_name;//时间超过申诉期的跟有评价过的都是成交期
                // dump($item['contact_one_order_by_is_important']['name'] . '  '.$status_name);
                $datas[$list_type][] = [
                    'company_name' => $item['mate_customer_one']['company_name'],
                    'mate_id' => $item['customer_mate_id'] ? $item['customer_mate_id'] : $item['customer_id'],
                    'address' => $item['mate_customer_one']['address'],
                    'status_name' => $status_name,
                    'status'=>$status,
                    'u_name' => $item['contact_one_order_by_is_important']['name'],
                    'mobile' => $item['contact_one_order_by_is_important']['mobile'],
                    't_name' => $item['customer_mate_follow_one']['user_one']['name'],
                ];
            }elseif ($type==3){
                $datas['pend'][] = [
                    'company_name' => $item['mate_customer_one']['company_name'],
                    'mate_id' => $item['customer_mate_id'] ? $item['customer_mate_id'] : $item['customer_id'],
                    'address' => $item['mate_customer_one']['address'],
                    'status_name' => '',
                    'status'=>0,
                    'u_name' => $item['contact_one_order_by_is_important']['name'],
                    'mobile' => $item['contact_one_order_by_is_important']['mobile'],
                    't_name' => $item['customer_mate_follow_one']['user_one']['name'],
                ];
            }
            unset($item);
        }
        //_debug($res_data['r']);
    // allDisposeTotal：审核通过 not_evaluate_total：未评价 not_approache_total:未接洽(撮合期)  completeDisposeTotal：审核通过已评价 notDisposeTotal：审核通过未评价（评论期）
        $datas['disposeTotal'] = $res_data['r']['disposeTotal'];
        _output($datas);
    }

    /**
     * 服务评价列表
     */
    public function serviceEvaluate(){
        $type = I('type',4);
        $brm_id = $this->brm_id;
        $page = I('page',1);
        $limit = I('limit',100);
        $url=$this->api_url.'/customer/getMatelist';
        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $dispose_status=I('status',0);
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'page'=>$page,
            'type'=>$type, //1行业大数据 2精准 3人工筛选 4意向
            'limit'=>$limit,
            'dispose_status'=>$dispose_status, //1已处理 2未处理  0或空为全部
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);
        $datas = [
            'lists'=>[],
        ];
        $count = 0;
        foreach ($res_data['r']['data'] as $key=>$item) {
            if($item['evaluate_level']!=0){
                $datas['lists'][] = [
                    'company_name' => $item['mate_customer_one']['company_name'],
                    'mate_id' => $item['customer_mate_id'] ? $item['customer_mate_id'] : $item['customer_id'],
                    'avatar_url' => $item['user_one']['avatar_url']? $this->image_url.$item['user_one']['avatar_url'] : '',
                    'name' => $item['user_one']['name'],
                    'star_level'=>$item['evaluate_level'],
                    'evaluate_content' => $item['evaluate_content'],
                    'evaluate_at' => $item['evaluate_at']?$item['evaluate_at']:'',
                ];
                $count++;
            }
        }
        _output($datas);
    }

    /**
     * 联系人详情
     */
    public function yxcontactsinfo(){
        $url=$this->api_url.'/yxbApplet/getContactById';
        $brm_id = $this->brm_id;
        $contacts_id = I('contacts_id');
        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'customer_contacts_id'=>$contacts_id,
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);
        if($res_data['r']['is_decision']==1){
            $is_decision='是';
        }else{
            $is_decision='不是';
        }
        if($res_data['r']['sex']==1){
            $sex='男';
        }else{
            $sex='女';
        }
        $result = [
            'name' => $res_data['r']['name'],
            'role' => $res_data['r']['role_title'],
            'mobile' => $res_data['r']['mobile'],
            'telephone' => $res_data['r']['telephone'],
            'qq' => $res_data['r']['qq'],
            'wechat' => $res_data['r']['wechat'],
            'email' => $res_data['r']['email'],
            'is_decision' => $is_decision,//决策人
            'sex'=>$sex,
            'department'=>$res_data['r']['department'],//部门
            'position'=>$res_data['r']['position'],//职位
        ];
        _output($result);
    }

    /**
     * 拓客人员服务详情
     */
    public function yxcustomeruser(){
        $url=$this->api_url.'/customer/getFollowUserCount';
        $brm_id = $this->brm_id;

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);
        $datas = [];
        foreach ($res_data['r'] as $key=>$item) {
            $datas[] = [
                'customer_id' => $item['customer_id'],
                'user_id' => $item['user_one']['customer_id'],
                'name' => $item['user_one']['name'],
                'mobile' => $item['user_one']['mobile'],
                'mail' => $item['user_one']['mail'],
                'avatar_url' => $item['user_one']['avatar_url']? $this->image_url.$item['user_one']['avatar_url'] : '',
                'total_push' => $item['total_push'],
                'this_push' => $item['this_push'],
                'total_tel' => $item['total_tel'],
                'this_tel' => $item['this_tel'],
            ];
        }
        _output($datas);
    }

    /**
     * 日报
     */
    public function reportday(){
        $url=$this->api_url.'/customer/getFollowCount';

        $day = I('day');
        $brm_id = $this->brm_id;
        $start_time=$day;
        $end_time=$day;

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'start_time'=>$start_time.' 00:00:00',
            'end_time'=>$end_time.' 23:59:59',
            'day_type'=>1,// (1日，2月，3年)
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);

        $r = $res_data['r'];
        $result['head']=['total_customer'=>$r['total_push']];
        $result['box']=[
            [
                'num'=>$r['total_tel']?$r['total_tel']:0,
                'message'=>'电话总量'
            ],
            [
                'num'=>$r['day_tel']?$r['day_tel']:0,
                'message'=>'平均每天电话量'
            ],
            [
                'num'=>$r['day_customer']?$r['day_customer']:0,
                'message'=>'每日筛选（跟进）客户'
            ],
            [
                'num'=>$r['total_push']?$r['total_push']:0,
                'message'=>'推送意向客户量'
            ]
        ];
        $result['list_tel'] = $r['list_tel'];
        _output($result);
    }


    /**
     * 周报
     */
    public function reportweek(){
        $url=$this->api_url.'/customer/getFollowCount';
        $brm_id = $this->brm_id;
        $start_time=I('start_time');
        $end_time=I('end_time');

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'start_time'=>$start_time.' 00:00:00',
            'end_time'=>$end_time.' 23:59:59',
            'day_type'=>1,// (1日，2月，3年)
        );

        $res = post($url,$data);
        $res_data=json_decode($res,true);

        $r = $res_data['r'];
        $result['head']=['total_customer'=>$r['total_push']];
        $result['box']=[
            [
                'num'=>$r['total_tel']?$r['total_tel']:0,
                'message'=>'电话总量'
            ],
            [
                'num'=>$r['day_tel']?$r['day_tel']:0,
                'message'=>'平均每天电话量'
            ],
            [
                'num'=>$r['day_customer']?$r['day_customer']:0,
                'message'=>'每日筛选（跟进）客户'
            ],
            [
                'num'=>$r['total_push']?$r['total_push']:0,
                'message'=>'推送意向客户量'
            ]
        ];
        _output($result);
    }

    /**
     * 月报
     */
    public function reportmonth(){
        $url=$this->api_url.'/customer/getFollowCount';
        $day = I('day');
        $brm_id = $this->brm_id;
        if(!$day||!$brm_id){
            _output([],201,'参数缺失');
        }
        $start_time=$day;

        if(($day!=date('Y-m'))) {
            $end_time = date('Y-m', strtotime('+1 month', strtotime($day.'-01'))).'-01 00:00:00';
        }else{
            $end_time = date('Y-m-d H:i:s',time());
        }

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'start_time'=>$start_time.'-01 00:00:00',
            'end_time'=>$end_time,
            'day_type'=>2,// (1日，2月，3年)
        );

        $res = post($url,$data);
        $res_data=json_decode($res,true);

        $r = $res_data['r'];
        $result['head']=['total_customer'=>$r['total_push']];
        $result['box']=[
            [
                'num'=>$r['total_tel']?$r['total_tel']:0,
                'message'=>'电话总量'
            ],
            [
                'num'=>$r['day_tel']?$r['day_tel']:0,
                'message'=>'平均每天电话量'
            ],
            [
                'num'=>$r['day_customer']?$r['day_customer']:0,
                'message'=>'每日筛选（跟进）客户'
            ],
            [
                'num'=>$r['total_push']?$r['total_push']:0,
                'message'=>'推送意向客户量'
            ]
        ];

        //电话量图表
        $start_time=$day.'-01';

        if(($day!=date('Y-m'))) {
            $end_time = date('Y-m', strtotime('+1 month', strtotime($start_time))).'-01 00:00:00';
        }else{
            $end_time = date('Y-m-d H:i:s',time());
        }

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'start_time'=>$start_time.' 00:00:00',
            'end_time'=>$end_time,
            'day_type'=>1,// (1日，2月，3年)
        );

        $res = post($url,$data);
        $res_data=json_decode($res,true);

        $r = $res_data['r'];

        if(!$r['list_tel']){
            $r['list_tel'][$day.'-01'] =  [
                'total' => 0
            ];
        }

        $result['list_tel'] = $r['list_tel'];
        _output($result);
    }

    /**
     * 年报
     */
    public function reportyear(){
        $url=$this->api_url.'/customer/getFollowCount';

        $day = I('day');
        $brm_id = $this->brm_id;

        if(!$day||!$brm_id){
            _output([],201,'参数缺失');
        }
        $start_time=$day;
        if(($day!=date('Y'))) {
            $end_time = date('Y', strtotime('+1 year', strtotime($day.'-01-01'))).'-01-01 00:00:00';
        }else{
            $end_time = date('Y-m-d H:i:s',time());
        }

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'start_time'=>$start_time.'-01-01 00:00:00',
            'end_time'=>$end_time,
            'day_type'=>3,// (1日，2月，3年)
        );

        $res = post($url,$data);
        $res_data=json_decode($res,true);

        $r = $res_data['r'];
        $result['head']=['total_customer'=>$r['total_push']];
        $result['box']=[
            [
                'num'=>$r['total_tel']?$r['total_tel']:0,
                'message'=>'电话总量'
            ],
            [
                'num'=>$r['day_tel']?$r['day_tel']:0,
                'message'=>'平均每天电话量'
            ],
            [
                'num'=>$r['day_customer']?$r['day_customer']:0,
                'message'=>'每日筛选（跟进）客户'
            ],
            [
                'num'=>$r['total_push']?$r['total_push']:0,
                'message'=>'推送意向客户量'
            ]
        ];

        //电话量图表
        $start_time=$day.'-01-01';
        if(($day!=date('Y'))) {
            $end_time = date('Y', strtotime('+1 year', strtotime($start_time))).'-01-01 00:00:00';
        }else{
            $end_time = date('Y-m-d H:i:s',time());
        }

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'start_time'=>$start_time.' 00:00:00',
            'end_time'=>$end_time,
            'day_type'=>2,// (1日，2月，3年)
        );

        $res = post($url,$data);
        $res_data=json_decode($res,true);

        $r = $res_data['r'];

        if(!$r['list_tel']){
            $r['list_tel'][$day.'-01'] =  [
                'total' => 0
            ];
        }

        $result['list_tel'] = $r['list_tel'];
        _output($result);
    }

    /**
     * 所有跟进记录
     * mobile_status 0:未联系  1:正常 2:未接 3:拒接 4:停机 5:电话空号 6:中途挂机',
     */
    public function record(){
        $url=$this->api_url.'/yxbApplet/allMateFollowList';
        $brm_id = $this->brm_id;
        $p=I('p',1);
        $limit=I('limit',500);
        $reply_status=I('reply_status',0);

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'p'=>$p,
            'limit'=>$limit,
            'search[reply_status]'=>$reply_status   //1成交期  2未评价
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);
        $datas['count'] = [
            'count' => $res_data['r']['count'],
            'notReplyTotal' => $res_data['r']['notReplyTotal'],
            'completeReplyTotal' => $res_data['r']['completeReplyTotal']
        ];
        $datas['had'] = [];
        $datas['wait'] = [];

        foreach ($res_data['r']['list'] as $item) {
            $list_type = 'wait';
            if(count($item['mate_follow_reply_count'])>0){
                $list_type = 'had';
            }
            $list_type = 'wait';//全部列表
            $item['fileinfo'] = json_decode($item['fileinfo'],true);
            $src_lists = [];
            foreach ($item['fileinfo'] as $key=>&$v) {
                $v['src'] = str_replace('http://','https://',$v['src']);
                if($v['filetype']=='image'){
                    if(count($src_lists)==0) {
                        $src_lists[] = $v['src'];
                    }else{
                        unset($item['fileinfo'][$key]);
                    }
                }
                unset($v);
            }
            foreach ($item['fileinfo'] as &$v) {
                if($v['filetype']=='image'){
                    $v['src_lists'] = implode(',',$src_lists);
                }
                unset($v);
            }
            $temp = [
                'follow_id'=>$item['customer_mate_follow_id'],
                'customer_mate_id'=>$item['customer_mate_id'],
                'user_id'=>$item['user_id'],
                'follow_explain'=>$item['follow_explain'],
                'contact_name'=>$item['contact_name'],
                'contact_mobile'=>$item['contact_mobile'],
                'name'=>$item['user_one']['name'],
                'avatar_url'=>$item['user_one']['avatar_url']?$this->image_url.$item['user_one']['avatar_url']:'',
                'customer_id'=>$item['customer_id'],
                'company_name'=>$item['company_name'],
                'created_at'=>$item['created_at'],//跟进时间
                'next_follow_at'=>$item['next_follow_at'],//建议下次跟进时间
                'mate_follow_replys'=> $item['mate_follow_replys'],
                'reply_count'=>count($item['mate_follow_replys']),
                'mobile_status'=>mobile_status($item['mobile_status']),
                'approached_advise'=>_substr($item['approached_advise'],100),
                'next_approached_at'=>$item['next_approached_at']?$item['next_approached_at']:$item['next_approached_text'],
                'is_comfirm_push'=>$item['is_comfirm_push'],
                'fileinfo'=>$item['fileinfo'],
                'record'=>$item['record'],
                'follow_prop' => $item['follow_prop'] ? json_decode($item['follow_prop'],true) : ''
            ];

            if($item['customer_mate_follow_id']==59867) {
            }
            $datas[$list_type][] = $temp;
        }
        //_debug($datas);
        _output($datas);
    }

    /**
     * 意向客户mate_id获取跟进列表
     */
    public function recordbymateid(){
        $url=$this->api_url.'/customer/getCustomerInfo';
        $brm_id = $this->brm_id;
        $mate_id=I('mate_id');
        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'mate_id'=>$mate_id
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);
        //_debug($res_data);
        $style = [
            1=>'icon-iconfontshouji',
            2=>'icon-zuoji',
            3=>'icon-weixin',
            4=>'icon-xinxi'
        ];
        foreach ($res_data['r']['follows'] as $k=>&$item){

            $item['fileinfo'] = json_decode($item['fileinfo'],true);
            $src_lists = [];
            foreach ($item['fileinfo'] as &$v) {
                $v['src'] = str_replace('http://','https://',$v['src']);
                if($v['filetype']=='image'){
                    $src_lists[] = $v['src'];
                }
                unset($v);
            }
            foreach ($item['fileinfo'] as &$v) {
                if($v['filetype']=='image'){
                    $v['src_lists'] = implode(',',$src_lists);
                }
                unset($v);
            }

            $item['company_name']  = $res_data['r']['info']['company_name'];
            $item['name']  = $res_data['r']['info']['sale_user_name'];
            $item['follow_id'] = $item['customer_mate_follow_id'];
            $item['follow_mode'] = $item['follow_mode'];
            $item['follow_mode_css'] = $style[$item['follow_mode']];
            $item['reply_count'] = count($item['mate_follow_replys']);
            $item['mobile_status'] = mobile_status($item['mobile_status']);
            $item['next_approached_at']=$item['next_approached_at']?$item['next_approached_at']:$item['next_approached_text'];
            $item['follow_prop'] = $item['follow_prop'] ? json_decode($item['follow_prop'],true) : '';
            unset($item);
        }
        foreach ($res_data['r']['contacts'] as &$item) {
            $item['linkman_role_name'] = linkman_role($item['linkman_role_id']);
            unset($item);
        }

        $result['had'] = $res_data['r']['follows'] ? $res_data['r']['follows'] : [];
        $result['contacts'] = $res_data['r']['contacts'];
        _output($result);
    }

    /**
     * 跟进记录详情
     */
    public function recordDetail(){
        $url=$this->api_url.'/yxbApplet/allMateFollowList';
        $brm_id = $this->brm_id;
        $p=I('p',1);
        $limit=I('limit',1000);
        $follow_id=I('customer_id');
        $be_replay_name=I('brname');
        $reply_status=I('reply_status',2);
        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'p'=>$p,
            'limit'=>$limit,
            'reply_status'=>$reply_status   //1成交期  2未评价
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);
        foreach ($res_data['r']['list'] as $item) {
            if($follow_id==$item['customer_mate_follow_id']) {
                if($item['user_one']['avatar_url']){
                    $avatar_url = $this->image_url.$item['user_one']['avatar_url'];
                }
                foreach ($item['mate_follow_replys'] as &$v) {
                    $v['right'] = 'item';
                    if($v['reply_name']==$be_replay_name){
                        $v['right'] = 'itemright';
                    }
                    $v['created_at'] = date('Y.m.d H:i:s',strtotime($v['created_at']));
                    unset($v);
                }

                $item['fileinfo'] = json_decode($item['fileinfo'],true);
                $src_lists = [];
                foreach ($item['fileinfo'] as &$v) {
                    $v['src'] = str_replace('http://','https://',$v['src']);
                    if($v['filetype']=='image'){
                        $src_lists[] = $v['src'];
                    }
                    unset($v);
                }
                foreach ($item['fileinfo'] as &$v) {
                    if($v['filetype']=='image'){
                        $v['src_lists'] = implode(',',$src_lists);
                    }
                    unset($v);
                }

                $yxcustomerinfo = $this->getYxcustomerInfo($brm_id, $item['customer_mate_id']);
                $temp = [
                    'follow_id'=>$item['customer_mate_follow_id'],
                    'customer_mate_id'=>$item['customer_mate_id'],
                    'user_id'=>$item['user_id'],
                    'follow_explain'=>$item['follow_explain'],
                    'contact_name'=>$item['contact_name'],
                    'contact_mobile'=>$item['contact_mobile'],
                    'name'=>$item['user_one']['name'],
                    'avatar_url'=>$avatar_url,
                    'customer_id'=>$item['customer_id'],
                    'company_name'=>$item['company_name'],
                    'created_at'=>$item['created_at'],//跟进时间
                    'next_follow_at'=>$item['next_follow_at'],//建议下次跟进时间
                    'mate_follow_replys'=> $item['mate_follow_replys'],
                    'reply_count'=>count($item['mate_follow_replys']),
                    'mobile_status'=>mobile_status($item['mobile_status']),
                    'is_comfirm_push'=>$item['is_comfirm_push'],
                    'approached_advise'=>$item['approached_advise'],
                    'next_approached_at'=>$item['next_approached_at']?$item['next_approached_at']:$item['next_approached_text'],
                    'is_comfirm_push'=>$item['is_comfirm_push'],
                    'fileinfo'=>$item['fileinfo'],
                    'records'=>$item['records'],
                    'yxcustomer'=>$yxcustomerinfo
                ];
                $datas[] = $temp;
            }
        }
        _output($datas);
    }

    /**
     * 提交跟进记录
     */
    public function subRecord(){
        $url=$this->api_url.'/yxbApplet/addMateFollowReply';
        $brm_id = $this->brm_id;
        $mate_follow_id=I('mate_follow_id');
        $reply_name=I('reply_name');
        $be_reply_name=I('be_reply_name');
        $reply_content=I('reply_content');

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'customer_mate_follow_id'=>$mate_follow_id,
            'reply_name'=>$reply_name,
            'be_reply_name'=>$be_reply_name,
            'reply_content'=>$reply_content,
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);
        if($res_data['s']=='-1'){
            _output([],201,$res_data['m']);
        }else{
            _output();
        }
    }

    /**
     * 评价拓客专员 yxbApplet
     * 3、mate_id ,evaluate_content,evaluate_level
     */
    public function subComment(){
        $url=$this->api_url.'/customer/addEvaluate';
        $brm_id = $this->brm_id;
        $type = I('type',3);
        $mate_id = I('mate_id');
        $evaluate_level = I('evaluate_level');
        $evaluate_content = I('evaluate_content');
        $approached = I('approached');
        $approached_at = I('approached_at');

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'type'=>3,
            'token'=>$token,
            'brm_id'=>$brm_id,
            'mate_id'=>$mate_id,
            'evaluate_level'=>$evaluate_level,
            'evaluate_content'=>$evaluate_content,
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);
        if($res_data['s']=='-1'){
            _output([],201,$res_data['m']);
        }else{
            _output();
        }
    }

    /**
     * 提交初步接洽情况
     * 1、mate_id,approached,approached_at
     * 2、mate_id,return_explain
     * 3、mate_id,evaluate_content,evaluate_level
     */
    public function subCall(){
        $url=$this->api_url.'/customer/addEvaluate';
        $brm_id = $this->brm_id;
        $mate_id = I('mate_id');
        $approached = I('approached');
        $approached_at = I('approached_at');

        //新增接洽状态、退回理由
        $type = I('type', 1);
        if($type==2) {
            $return_explain = json_encode(['reason'=>I('return_explain'),'type'=>4]);
        }

        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'mate_id'=>$mate_id,
            'approached'=>$approached,
            'type'=>$type,
            'return_explain'=>$return_explain,
            'approached_at'=>date('Y-m-d H:i:s'),
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);

        if($res_data['s']=='-1'){
            _output([],201,$res_data['m']);
        }else{
            _output();
        }
    }

    /**
     *获取评价详情（接洽情况、评价）
     */
    public function commentInfo(){
        $url=$this->api_url.'/yxbApplet/getEvaluate';
        $brm_id = $this->brm_id;
        $mate_id = I('mate_id');
        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'mate_id'=>$mate_id
        );
        $res = post($url,$data);
        $res_data=json_decode($res,true);
        $res_data['r']['customerMateFollowOne']['fileinfo'] = json_decode($res_data['r']['customerMateFollowOne']['fileinfo'],true);

        $src_lists = [];
        foreach ($res_data['r']['customerMateFollowOne']['fileinfo'] as &$item) {
            $item['src'] = str_replace('http://','https://',$item['src']);
            if($item['filetype']=='image'){
                $src_lists[] = $item['src'];
            }
            unset($item);
        }
        foreach ($res_data['r']['customerMateFollowOne']['fileinfo'] as &$item) {
            if($item['filetype']=='image'){
                $item['src_lists'] = implode(',',$src_lists);
            }
        }

        //待评论总数
        $url=$this->api_url.'/customer/getCustomerInfo';
        $token= md5($brm_id.'_'.md5(substr(time(), 0,4)).'_PlIM-lJ54-940R-J2K8-JudM');
        $data = array(
            'token'=>$token,
            'brm_id'=>$brm_id,
            'mate_id'=>$mate_id
        );
        $res = post($url,$data);
        $evaluate_res_data=json_decode($res,true);


        $result['had'] = $evaluate_res_data['r']['follows'] ? $evaluate_res_data['r']['follows'] : [];
        $res_data['r']['notReplyTotal'] = count($result['had']);

        _output($res_data['r']);
    }

    /**
     * 发送消息模版
     */
    public function sendMsg()
    {
        $openid = I('openid');
        $form_id = I('form_id');
        //$form_id = '20da6d6a610657cbef0da01646523582';
        //$openid = 'oB7II0e9gfXw5Dr_BDsRyIbHZ7L4';
        if(!$openid){
            _output([],201,'未授权登陆，无法发送消息');
        }
        $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . C('WX.appid') . "&secret=" . C('WX.secret');
        $res = getRemoteData($token_url);
        $res = json_decode($res, true);
        $send_msg_url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $res['access_token'];
        $data = [
            "touser" => $openid,
            "template_id" => "m1xxlKbo8V9TUSTKENAun4SfW0eAwPFr0moKklD1Cn4",
            "page" => "index",
            "form_id" => $form_id,
            "data" => [
                "keyword1" => [
                    "value" => "258集团",
                    "color" => "#173177"
                ],
                "keyword2" => [
                    "value" => date('Y年m月d日 H:i:s'),
                    "color" => "#173177"
                ]
            ],
            "emphasis_keyword" => "keyword1.DATA"
        ];
        $msg_res = $this->https_request($send_msg_url,$data,'json');
    }

    public function sendCustomerMsg(){
        $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . C('WX.appid') . "&secret=" . C('WX.secret');
        $res = getRemoteData($token_url);
        $res = json_decode($res, true);

        $send_msg_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$res['access_token'];
        $openid = 'oB7II0e9gfXw5Dr_BDsRyIbHZ7L4';
        $data = [
            "touser"=>$openid,
            "msgtype"=>"text",
            "text"=>[
                "content"=>"Hello World"
            ]
        ];
        $msg_res = $this->https_request($send_msg_url,$data,'json');
    }

    function https_request($url,$data,$type){
        if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
            $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
            $data=json_encode($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 客服消息
     */
    public function message(){
        if ($this->checkSignature()) {
            $file_in = file_get_contents("php://input"); //接收post数据
            $xml = simplexml_load_string($file_in);//转换post数据为simplexml对象
            foreach($xml->children() as $child)    //遍历所有节点数据
            {
                $sava_data = $child->getName() . ": " . $child . ""; //打印节点名称和节点值
            }
            require_once(APP_PATH."Common/Extend/Wxmsg/wxBizMsgCrypt.class.php");

            $post_data = array (
                'signature' => '5a906652eac516d9c7534f1cf7995cf4c373cfec',
                'timestamp' => '1496417474',
                'nonce' => '242808465',
                'openid' => 'oB7II0e9gfXw5Dr_BDsRyIbHZ7L4',
                'encrypt_type' => 'aes',
                'msg_signature' => '182e67e36dfe312e4805cd5978fae13d68d9d521',
            );
            // 第三方发送消息给公众平台
            $encodingAesKey = C('XCX_MSG.encodingAesKey');
            $token = "yingxiaobao";
            $timeStamp = "1409304348";
            $nonce = "xxxxxx";
            $appId = "wx9965d43f8b4f56de";
            $text = "<xml><ToUserName><![CDATA[oia2Tj我是中文jewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Description><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>";

            $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
            $encryptMsg = '';
            $errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
            if ($errCode == 0) {
                print("加密后: " . $encryptMsg . "\n");
            } else {
                print($errCode . "\n");
            }

            $xml_tree = new \DOMDocument();
            $xml_tree->loadXML($encryptMsg);
            $array_e = $xml_tree->getElementsByTagName('Encrypt');
            $array_s = $xml_tree->getElementsByTagName('MsgSignature');
            $encrypt = $array_e->item(0)->nodeValue;
            $msg_sign = $array_s->item(0)->nodeValue;

            $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
            $from_xml = sprintf($format, $encrypt);

            // 第三方收到公众号平台发送的消息
            $msg = '';
            $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
            if ($errCode == 0) {
                print("解密后: " . $msg . "\n");
            } else {
                print($errCode . "\n");
            }
        }
    }

    /**
     * 验证数据是否来自微信服务端
     * @return bool
     */
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = C('XCX_MSG.token');;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 二维码规则
     */
    public function ewm(){

    }
}
